//
//  UIImage+SaveImage.m
//  TGVendor
//
//  Created by lwc on 2018/8/29.
//  Copyright © 2018年 jzg. All rights reserved.
//

#import "UIImage+SaveImage.h"
#import <Photos/Photos.h>
#import <SVProgressHUD.h>

@implementation UIImage (SaveImage)

- (void)saveToAlbum:(void (^)(NSError *))result{
    [self setSaveResult:result];
    
    PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == PHAuthorizationStatusDenied) { // 用户拒绝当前App访问相册
                if (oldStatus != PHAuthorizationStatusNotDetermined) {
                    [SVProgressHUD showErrorWithStatus:@"若要保存图片请允许APP访问你的相册！"];
                }
            } else if (status == PHAuthorizationStatusAuthorized) { // 用户允许当前App访问相册
                UIImageWriteToSavedPhotosAlbum(self, self, @selector(image:didFinishSavingWithError:contextInfo:result:), (__bridge void *)self);
            } else if (status == PHAuthorizationStatusRestricted) { // 无法访问相册
                [SVProgressHUD showErrorWithStatus:@"因系统原因，无法访问相册！"];
            }
        });
    }];
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo result:(void (^)(NSError *))result{
    [self runSaveResult:error];
    //    self.saveImage ? self.saveImage(error) : nil;
//    self.saveImage = NULL;
//    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

- (void)setSaveResult:(void (^)(NSError *) )result{
    objc_setAssociatedObject(self, @"saveResult", result, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (void)runSaveResult:(NSError *)error{
    void (^result)(NSError *) = objc_getAssociatedObject(self, @"saveResult");
    if (result) {
        result(error);
    }
}

@end
